package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.CargueService;
import co.gov.medellin.ssti.sub.model.service.VflexService;
import co.gov.medellin.ssti.sub.model.vo.CargueVO;
import co.gov.medellin.ssti.sub.model.vo.VflexVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.StrutsUploadForm;

public class IngresarAction extends Action {
	@Autowired
	CargueService cargueServiceImpl;
	@Autowired
	VflexService vflexServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();

		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			HttpSession session = request.getSession();
			UserVO user = (UserVO) session.getAttribute("userInfo");
			String terminalAddress = "WEB=" + request.getRemoteAddr();
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

			String strnomcargue = request.getParameter("nombre_cargue");
			String strtipcargue = request.getParameter("tipo_cargue");
			String ingreso = request.getParameter("ingreso");
			List<VflexVO> tipoCargue = null;
			// request.setCharacterEncoding("utf-8");
			System.getProperty("file.encoding");
			if ((Object) ingreso != null) {
				if (ingreso.equals("true")) {
					try {
						CargueVO objcargueVO = new CargueVO();
						StrutsUploadForm myForm = (StrutsUploadForm) form;
						// Process the FormFile
						FormFile myFile = myForm.getTheFile();
						// String contentType = myFile.getContentType();
						String fileName = myFile.getFileName();
						// int fileSize = myFile.getFileSize();
						byte[] fileData = myFile.getFileData();

						objcargueVO.setNombre(strnomcargue);
						objcargueVO.setVflcodigo(strtipcargue);
						objcargueVO.setArchivo(fileName);

						String retorno[] = cargueServiceImpl.ingresarCargue(
								objcargueVO, user.getName(), terminalAddress,
								dateFormat.format(c.getTime()));

						if (retorno[0].equals("true")) {
							request.setAttribute("lote", retorno[1]);
							request.setAttribute("search", "ok");

							int lote = Integer.parseInt(retorno[1]);
							request.setAttribute("msg",
									"El archivo fue cargado satisfactoriamente en el lote numero "
											+ lote);
							int icargue = cargueServiceImpl.uploadFile(lote,
									fileData);

							if (icargue == -1) {
								request.setAttribute("lote", lote + "");
								return mapping.findForward("ingreso");
							} else if (icargue == 0) {
								request.setAttribute("msg",
										"Ocurrio un error al cargar el archivo..");
								return mapping.findForward("ingreso");
							} else {
								request.setAttribute("msg",
										"Ocurrio un error al cargar el archivo. Revise el registro numero "
												+ icargue
												+ " e intentelo de nuevo...");
								return mapping.findForward("ingreso");
							}

						} else {
							request.setAttribute("msg",
									"No se pudo cargar el archivo, el nombre ya existe!!");
							return mapping.findForward("ingreso");
						}
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
						session.setAttribute("msg",
								"No se pudo cargar el archivo..");
						return mapping.findForward("fail");
					}
				}
			}

			try {
				tipoCargue = (List<VflexVO>) vflexServiceImpl.findVflex(
						"TIPOS DE CARGUE AUTOMATICO", 1);
				String codeTipoBeneficiario = "";
				String codeTipoBeneficio = "";
				VflexVO vflexVO = null;
				for (int i = 0; i < tipoCargue.size(); i++) {
					vflexVO = (VflexVO) tipoCargue.get(i);
					if (vflexVO.getNombreVflex().equals("BENEFICIARIOS")) {
						codeTipoBeneficiario = vflexVO.getCode().toString();
					} else if (vflexVO.getNombreVflex().equals("BENEFICIOS")) {
						codeTipoBeneficio = vflexVO.getCode().toString();
					}
				}
				request.setAttribute("codeTipoBeneficiario",
						codeTipoBeneficiario);
				request.setAttribute("codeTipoBeneficio", codeTipoBeneficio);
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}

		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");
	}
}